//
//  PostMessageView.m
//  testPost
//
//  Created by 刘锦锋 on 16/7/11.
//  Copyright © 2016年 com.ljf. All rights reserved.
//

#import "PostImageView.h"
#import "ImageCollectionViewCell.h"
#import "TZImagePickerController.h"
#import "JKImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface PostImageView ()<UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,JKImagePickerControllerDelegate>

@property (nonatomic, weak) UIViewController *vc;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (strong , nonatomic) NSMutableArray * selectPicArry;

@property (strong,nonatomic) NSMutableArray * fininalArry;


@end

@implementation PostImageView

- (instancetype)initWithFrame:(CGRect)frame superVC:(UIViewController *)vc
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _imageArr = [NSMutableArray array];
        NSMutableDictionary * beforeDic =  [Tools getValueFromNSUserDefaultsByKey:PICIMG_ARR];
        self.selectPicArry = beforeDic[PICIMG_ARR];
        if (self.selectPicArry>0) {
            for (int i = 0; i<self.selectPicArry.count; i++) {
                
                NSLog(@"%@",self.selectPicArry[i]);

                NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString * documentsDirectory = [paths objectAtIndex:0];
                NSLog(@" 2----- documentsDirectory ==== %@",documentsDirectory);
                UIImage * beforeImg = [UIImage imageWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:self.selectPicArry[i]]];
                [self.imageArr addObject:beforeImg];
            }
            
        }
        _vc = vc;
        self.backgroundColor = [UIColor whiteColor];
        self.maxNum = 10;
        [self setUI];
    }
    return self;
}
///选择存储img的数组
-(NSMutableArray *)selectPicArry
{
    if (!_selectPicArry) {
        _selectPicArry = [NSMutableArray new];
    }
    return _selectPicArry;
}

- (void)setUI
{
    self.imgWidth =self.frame.size.height;
    self.imgHeight = self.frame.size.height;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;

    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(self.imgWidth,self.imgHeight);
    NSLog(@"self.imgHeight === %f",self.imgHeight);
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0,self.frame.size.width, self.imgHeight) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource =self;
    _collectionView.delegate =self;
    _collectionView.pagingEnabled =NO;
    _collectionView.showsHorizontalScrollIndicator = NO;

    [self addSubview:_collectionView];
    
    [_collectionView registerNib:[UINib nibWithNibName:@"ImageCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ImageCollectionViewCell"];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    if (self.imageArr.count >= self.maxNum)
//    {
//        return self.maxNum;
//    }else
//    {
        return self.imageArr.count ;
//    }
}
//返回cell.cell复用
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //复用
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCollectionViewCell" forIndexPath:indexPath];
    
    if (indexPath.row == self.imageArr.count)
    {
        cell.imageV.image = [UIImage imageNamed:@"common_btn_uploading"];
        cell.deleteBtn.hidden = YES;
        
    }else
    {
        cell.imageV.image = self.imageArr[indexPath.row];
        cell.deleteBtn.hidden = NO;
        cell.deleteBtn.tag = 100+indexPath.row;
        [cell.deleteBtn addTarget:self action:@selector(delImage:) forControlEvents:UIControlEventTouchUpInside];
    }
    cell.imageV.clipsToBounds = YES;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.imageArr.count && self.imageArr.count<=self.maxNum)
    {
        [self composePicAdd];
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //上下左右各偏移10个像素
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


-(void)delImage:(UIButton*)button
{
    NSLog(@"delet"); 
    
    [self.imageArr removeObjectAtIndex:button.tag-100];
    
    [self.collectionView reloadData];
}

- (void)composePicAdd
{
    JKImagePickerController *imagePickerController = [[JKImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.showsCancelButton = YES;
    imagePickerController.allowsMultipleSelection = YES;
    //imagePickerController.minimumNumberOfSelection = 3;
    imagePickerController.maximumNumberOfSelection = self.maxNum;
    //imagePickerController.selectedAssetArray = _imageArr;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [_vc presentViewController:navigationController animated:YES completion:NULL];
}


#pragma mark - JKImagePickerControllerDelegate
- (void)imagePickerController:(JKImagePickerController *)imagePicker didSelectAsset:(JKAssets *)asset isSource:(BOOL)source
{
    [imagePicker dismissViewControllerAnimated:YES completion:^
     {
         
     }];
}
- (void)imagePickerController:(JKImagePickerController *)imagePicker didSelectAssets:(NSArray *)assets isSource:(BOOL)source
{
    [self setImageWithAssetArr:assets];
    
    [imagePicker dismissViewControllerAnimated:YES completion:^
     {
         
     }];
    NSLog(@"assets ======= %@",assets[0]);
}

- (void)imagePickerControllerDidCancel:(JKImagePickerController *)imagePicker
{
    [imagePicker dismissViewControllerAnimated:YES completion:^
     {
         
     }];
}

- (void)setImageWithAssetArr:(NSArray *)arr;
{
    for (int i = 0; i<arr.count; i++)
    {
        JKAssets *asset = arr[i];
        
        ALAssetsLibrary  *lib = [[ALAssetsLibrary alloc] init];
        
        [lib assetForURL:asset.assetPropertyURL resultBlock:^(ALAsset *asset)
         {
             if (asset)
             {
                 if (_imageArr.count == self.maxNum)
                 {
                     [_collectionView reloadData];
                     return;
                 }
                 
                 UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];

//                 [_imageArr addObject:image];
                 [_imageArr insertObject:image atIndex:0];
               
                 
                 if (i == arr.count- 1)
                 {
                     [_collectionView reloadData];
                 }
             }
         } failureBlock:^(NSError *error)
         {
             
         }];
    }
    
      [self goSaveThePic];
    
}



-(void)goSaveThePic
{
    if (self.imageArr.count>0) {

 
    
    NSMutableDictionary * beforeDic =  [Tools getValueFromNSUserDefaultsByKey:PICIMG_ARR];
    self.selectPicArry = beforeDic[PICIMG_ARR];
//    if (self.selectPicArry>0) {
//        for (int i = 0; i<self.selectPicArry.count; i++) {
//            NSLog(@"%@",self.selectPicArry[i]);
//            
//            NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//            NSString * documentsDirectory = [paths objectAtIndex:0];
//            NSLog(@" 2----- documentsDirectory ==== %@",documentsDirectory);
//            UIImage * beforeImg = [UIImage imageWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:self.selectPicArry[i]]];
//            [self.imageArr addObject:beforeImg];
//        }
//        
//    }
   
    //UIImagePNGRepresentation     将image转成PNG格式二进制数据
    //UIImageJPEGRepresentation    将image转成JPG格式二进制数据
    //将UIImage转NSdata
    
    //第一个参数   需要转化的image对象
    //第二个参数   压缩比例
    //    NSData *data1 = UIImageJPEGRepresentation(info[@"UIImagePickerControllerEditedImage"], 0.00001);
        NSMutableArray * fininalArr = [NSMutableArray new];
    for (int i = 0; i<self.imageArr.count; i++) {
        NSData *data2 = UIImageJPEGRepresentation(self.imageArr[i], 0.00001);
        
        //取到沙盒路径
      
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSLog(@" 1----- documentsDirectory ==== %@",documentsDirectory);
        //    [data1 writeToFile:[homePath stringByAppendingString:@"/Documents/left1.jpg"] atomically:YES];
        NSString * savePicStr = [NSString stringWithFormat:@"Pesronal%d.jpg",i];
        [data2 writeToFile:[documentsDirectory stringByAppendingPathComponent:savePicStr] atomically:NO];
        [fininalArr addObject:(NSString *)savePicStr];
//        [self.selectPicArry addObject:savePicStr];
        
    }
    NSMutableDictionary * savePicDic = [NSMutableDictionary new];
        [fininalArr addObjectsFromArray:self.selectPicArry];
    [savePicDic setObject:fininalArr forKey:PICIMG_ARR];
    [Tools syncNSUserDeafaultsByKey:PICIMG_ARR withValue:savePicDic];
    }
}


@end
